package com.choosefine.it.common.aop;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.choosefine.it.common.def.CommonConstant;
import com.github.pagehelper.PageInfo;

/**
 * Created by 邱鹏 on 12/23/15.
 */
@Aspect            //定义一个切面
@Configuration
public class GetMappingPageAop {
    private static final Logger logger = LoggerFactory.getLogger("api service v1");
//    @Autowired
//    ObjectMapper jsonObjectMapper;

    /**
     * 处理拦截到接口访问请求，进行分页判断
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around(value = "@annotation(org.springframework.web.bind.annotation.GetMapping))&&execution(public * com.choosefine.it..*.*Controller.*(..)")
    public Object doAroundIsAllowedIp(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("-----------------------对--GetMapping--接--口--进--行--事--前--拦--截--------------------------------");
        Object result = null;
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();//获取request
        String queryString = request.getQueryString();
        String token = request.getParameter("token");
        String userId = request.getParameter("userId");

        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        String thisMethod = method.getName();//当前函数的名称
        String fullName = signature.getDeclaringTypeName() + "." + pjp.getSignature().getName();
        Object[] args = pjp.getArgs();//被拦截方法的所有参数

        //分页检查
        checkPage(args);

        result = pjp.proceed();
        logger.info("--->--->--->--->--->GetMapping执行完毕进行的收尾工作  <---<---<---<---<---<---");
        return result;
    }

    /**
     * 分页检查
     *
     * @param args
     */
    private void checkPage(Object[] args) {
        for (Object arg : args) {
            if (arg instanceof PageInfo) {
                PageInfo pageInfo = (PageInfo) arg;
                if (pageInfo.getPageNum() == CommonConstant.FLAG_ZERO) {
                    pageInfo.setPageNum(CommonConstant.DEFAULT_PAGE_NUM);
                }
                if (pageInfo.getPageSize() == CommonConstant.FLAG_ZERO) {
                    pageInfo.setPageSize(CommonConstant.DEFAULT_PAGE_SIZE);
                }
            }
        }

    }
}